package com.example.votemanage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.votemanage.config.AuthAccess;
import com.example.votemanage.config.Result;
import com.example.votemanage.entity.AuctionRecord;
import com.example.votemanage.service.Impl.AuctionRecordServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AuctionRecordController {
    @Autowired
    AuctionRecordServiceImpl auctionRecordService;
    @GetMapping("/all")
    public Page<AuctionRecord> getAuctionRecords(@RequestParam(defaultValue = "1") int page,
                                                 @RequestParam(defaultValue = "10") int size) {
        return auctionRecordService.getAuctionRecordWithDetails(page, size);
    }
    @GetMapping("/selectRecord")
    public List<AuctionRecord> getAuctionList(@RequestParam Integer auctionId) {
        System.out.println("auctionId = " + auctionId);
        return auctionRecordService.getAuctionRecord(auctionId);
    }
    @GetMapping("/selectRecordMax")
    public List<AuctionRecord> selectRecordMax() {
        return auctionRecordService.selectRecordMax();
    }
    @GetMapping("/selectRecordMaxnext")
    public List<AuctionRecord> selectRecordMaxnext() {
        return auctionRecordService.selectRecordMaxnext();
    }
    @PostMapping("/add")
    public Result addOrUpdateAuctionRecord(@RequestBody AuctionRecord auctionRecord) {
        // 检查用户是否已经有该拍卖的记录
        QueryWrapper<AuctionRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", auctionRecord.getUserId())
                .eq("auctionId", auctionRecord.getAuctionId());
        AuctionRecord existingRecord = auctionRecordService.getOne(queryWrapper);
        boolean saveOrUpdateResult;
        if (existingRecord != null) {
            // 如果记录存在，更新记录的其他字段
            existingRecord.setAuctionPrice(auctionRecord.getAuctionPrice());
            existingRecord.setAuctionTime(auctionRecord.getAuctionTime());
            saveOrUpdateResult = auctionRecordService.updateById(existingRecord); // 更新记录
        } else {
            // 如果记录不存在，则新增一条记录
            saveOrUpdateResult = auctionRecordService.save(auctionRecord);
        }
        if (saveOrUpdateResult) {
            return Result.success(auctionRecord);
        } else {
            return Result.success("Failed to add or update auction record.");
        }
    }
}
